fastjson处理返回值为null的问题 - myth_g的博客 - CSDN博客

创建时间:2019/4/12 19:11
来源:https://blog.csdn.net/myth_g/article/details/80617722


版权声明:转载请注明作者 https://blog.csdn.net/myth_g/article/details/80617722
  1. 1
    <mvc:annotation-driven>
  2. 2
    <mvc:message-converters register-defaults="true">
  3. 3
    <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
  4. 4
    <property name="features">
  5. 5
    <array>
  6. 6
    <!-- 下面配置,默认是false-->
  7. 7
    <value>WriteMapNullValue</value>
  8. 8
    <value>WriteNullNumberAsZero</value>
  9. 9
    <value>WriteNullListAsEmpty</value>
  10. 10
    <value>WriteNullStringAsEmpty</value>
  11. 11
    <value>WriteNullBooleanAsFalse</value>
  12. 12
    <value>WriteDateUseDateFormat</value>
  13. 13
    </array>
  14. 14
    </property>
  15. 15
    </bean>
  16. 16
    </mvc:message-converters>
  17. 17
    </mvc:annotation-driven>
配置如上配置,字面意思是通过json返回类型自动将值设置成不为null的值.


springboot配置如下:

  1. 1
    @Configuration
  2. 2
    public class FastJsonMessage {
  3. 3
  4. 4
    @Bean
  5. 5
    public HttpMessageConverters fastJsonHttpMessageConverters() {
  6. 6
    //1、定义一个convert转换消息的对象
  7. 7
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
  8. 8
    //2、添加fastjson的配置信息
  9. 9
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
  10. 10
    /* fastJsonConfig.setSerializerFeatures(
  11. 11
    SerializerFeature.WriteEnumUsingToString,
  12. 12
    SerializerFeature.WriteNullStringAsEmpty,
  13. 13
    SerializerFeature.WriteMapNullValue,
  14. 14
    SerializerFeature.WriteDateUseDateFormat);*/
  15. 15
    fastJsonConfig.setSerializeFilters((ValueFilter) (o, s, source) -> {
  16. 16
    if (source == null) {
  17. 17
    return "";            //此处是关键,如果返回对象的变量为null,则自动变成""
  18. 18
    }
  19. 19
    if (source instanceof Date) {
  20. 20
    return ((Date) source).getTime();
  21. 21
    }
  22. 22
    return source;
  23. 23
    });
  24. 24
    //2-1 处理中文乱码问题
  25. 25
    List<MediaType> fastMediaTypes = new ArrayList<>();
  26. 26
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
  27. 27
    fastConverter.setSupportedMediaTypes(fastMediaTypes);
  28. 28
    //3、在convert中添加配置信息
  29. 29
    fastConverter.setFastJsonConfig(fastJsonConfig);
  30. 30
    //4、将convert添加到converters中
  31. 31
    HttpMessageConverter<?> converter = fastConverter;
  32. 32
    return new HttpMessageConverters(converter);
  33. 33
    }
  34. 34
    }
QuoteFieldNames———-输出key时是否使用双引号,默认为true 
WriteMapNullValue——–是否输出值为null的字段,默认为false 
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null 
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null 
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null 
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null